import turbogears           as tg
import cherrypy             as http

from turbogears             import identity, url
from fasttrack.model        import Project, status_codes, impact_codes, chance_codes
from fasttrack.utils        import getRecentChanges
from fasttrack              import utils


class RecentChangesController(object):
    @tg.expose(template="fasttrack.templates.recentchanges.index")
    @identity.require(identity.not_anonymous())
    def index(self):  
        utils.checkIdentity(http.request.identity.user)      
        all_projects = Project.select("parent_project_id is NULL order by upper(name)")
        
        projects = [project for project in all_projects if not project.archived]
        
        recent_proj = getRecentChanges(projects, self._timeframe())
        
        return dict(active_section='recentchanges',
                    recent_proj=recent_proj,
                    status_codes=status_codes,
                    chance_codes=chance_codes,
                    impact_codes=impact_codes,
                    time_hours=self._timeframe())
    
    
    @tg.expose()    
    def change_time(self, change_hours):
        http.response.simpleCookie['time_frame_id'] = change_hours
        http.response.simpleCookie['time_frame_id']['path'] = '/'
        
        raise http.HTTPRedirect(url('/recentchanges'))
        
    
    def _timeframe(self):
        if http.request.simpleCookie.has_key('time_frame_id'):
            return int(http.request.simpleCookie['time_frame_id'].value)
        return 24